﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace BenefitHelper.Sys
{
    /// <summary>
    /// 设定交易员可以看到的组
    /// </summary>
    public class OperatorCouldSeeGroups
    {
        public int Id { get; set; }

        public int OperatorId { get; set; }

        public virtual Operator Operator { get; set; }

        public int GroupId { get; set; }

        public virtual Groups Group { get; set; }

        public List<Groups> GetOperatorCouldSeeGroups(int operatorId, DB.DBManager db)
        {
            List<Groups> groups = new List<Groups>();
            var query = db.OperatorCouldSeeGroups.Where(a => a.OperatorId == operatorId).Include(a => a.Group).ToList();
            foreach (OperatorCouldSeeGroups g in query)
            {
                groups.Add(g.Group);
            }
            return groups;
        }
        public void Delete(DB.DBManager db)
        {
            var query = db.OperatorCouldSeeGroups;
            foreach (Sys.OperatorCouldSeeGroups g in query)
            {
                db.OperatorCouldSeeGroups.Remove(g);
            }
            db.SaveChanges();
        }
        /// <summary>
        /// 在每天的小组，组员绑定的时候对他们进行可查看小组的绑定
        /// </summary>
        /// <param name="operatorid"></param>
        /// <param name="groups"></param>
        public void ResetOperatorColuldSeeGroups(int operatorid, int groupid, DB.DBManager db)
        {
            //  Delete(db);
            var query = db.OperatorCouldSeeGroups.Where(a => a.OperatorId == operatorid).Where(a => a.GroupId == groupid);
            if (query.Count() == 0)
            {
                OperatorCouldSeeGroups s = new OperatorCouldSeeGroups();
                s.OperatorId = operatorid;
                s.GroupId = groupid;
                db.OperatorCouldSeeGroups.Add(s);
            }
            db.SaveChanges();
        }

        public void InitOperatorCouldSeeGroups(DB.DBManager db)
        {
            Delete(db);
            var query = db.Groups.ToList();
            foreach (BenefitHelper.Sys.Groups g in query)
            {
                int gid = g.Id;
                var operators = new BenefitHelper.Sys.Operator().GetUnDeletedOperators(db);
                foreach (BenefitHelper.Sys.Operator op in operators)
                {
                    if (Sys.VisitPrower.OperatorHasGroupPrower(op.Id, gid, db))
                    {
                        ResetOperatorColuldSeeGroups(op.Id, gid, db);
                    }
                }
            }
            db.SaveChanges();
        }
    }
}
